<template>
  <div>
    <p style="text-align: left">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="用户名">
          <el-input
            v-model="formInline.user_Name"
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input
            v-model="formInline.u_Name"
            placeholder="请输入姓名"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="tableData">查询</el-button>
        </el-form-item>
      </el-form>
      <el-button type="success" @click="dialogVisible = true">
        <el-icon><Plus /></el-icon>添加</el-button
      >
      <el-button type="danger" @click="batchDel"
        ><el-icon><Delete /></el-icon>>批量删除</el-button
      >
    </p>
    <br />
    <el-table
      :data="userList"
      border
      style="width: 100%; font-size: 12pt"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" align="center"></el-table-column>
      <el-table-column
        prop="User_Name"
        label="用户名"
        align="center"
      ></el-table-column>
      <el-table-column prop="User_PassWord" label="密码" align="center">
        ******</el-table-column
      >
      <el-table-column
        prop="U_Name"
        label="姓名"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="Job_number"
        label="工号"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="User_Phone"
        label="手机号"
        align="center"
      ></el-table-column>
      <el-table-column label="操作" align="center">
        <template v-slot="slot">
          <el-link type="danger" @click="delData(slot.row.User_Id)"
            >删除</el-link
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      v-model="dialogVisible"
      title="提示"
      width="45%"
      :before-close="handleClose"
    >
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="form"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <el-form-item label="用户名" prop="user_Name">
          <el-input v-model="form.user_Name" />
        </el-form-item>
        <el-form-item label="密码" prop="user_PassWord">
          <el-input v-model="form.user_PassWord" type="password" />
        </el-form-item>
        <el-form-item label="姓名" prop="u_Name">
          <el-input v-model="form.u_Name" />
        </el-form-item>
        <el-form-item label="工号" prop="job_number">
          <el-input v-model="form.job_number" />
        </el-form-item>
        <el-form-item label="手机号" prop="user_Phone">
          <el-input
            v-model.number="form.user_Phone"
            maxlength="11"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="权限" prop="RoleName">
          <el-checkbox-group v-model="checkList">
            <el-checkbox
              v-for="item in roleList"
              :key="item.RoleId"
              :value="item.RoleId"
              name="type"
            >
              {{ item.RoleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addUser(ruleFormRef)">
            添加
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="dialogVisibleUpdateUser"
      title="提示"
      width="45%"
      :before-close="handleClose"
    >
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="form"
        :rules="rulesUpdate"
        label-width="auto"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <el-form-item label="用户名" prop="user_Name">
          <el-input v-model="form.user_Name" />
        </el-form-item>
        <el-form-item label="密码" prop="user_PassWord">
          <el-input v-model="form.user_PassWord" type="password" />
        </el-form-item>
        <el-form-item label="姓名" prop="u_Name">
          <el-input v-model="form.u_Name" />
        </el-form-item>
        <el-form-item label="工号" prop="job_number">
          <el-input v-model="form.job_number" />
        </el-form-item>
        <el-form-item label="手机号" prop="user_Phone">
          <el-input
            v-model.number="form.user_Phone"
            maxlength="11"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="权限" prop="RoleName">
          <el-checkbox-group v-model="checkList">
            <el-checkbox
              v-for="item in roleList"
              :key="item.RoleId"
              :value="item.RoleId"
              name="type"
            >
              {{ item.RoleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="updateUser(ruleFormRef)">
            修改
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="dialogImportVisible"
      title="导入"
      width="30%"
      :before-close="handleClose1"
    >
      <span>下载模版</span>
      <a href="StaticFiles/用户列表.xlsx">点击下载</a>
      <br />
      <el-upload class="upload-demo" drag action="Users/ImportExcel" multiple>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </template>
      </el-upload>

      <span class="dialog-footer">
        <el-button @click="dialogImportVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleImport">确 定</el-button>
      </span>
    </el-dialog>

    <br />
    <table style="margin: auto">
      <tr>
        <td>
          <el-pagination
            v-model:current-page="page"
            v-model:page-size="size"
            :page-sizes="[10, 20, 30, 40]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </td>
      </tr>
    </table>
  </div>
</template>
<script lang="ts" setup>
import axios from "axios";
import { ref, reactive } from "vue";
import { FormInstance, FormRules, ElTable } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { UploadFilled } from "@element-plus/icons-vue";

const page = ref(1);
const size = ref(10);
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
const totalCount = ref(0);
const userList = ref([]);
const checkList = ref([]);
const roleList = ref([]);
const dialogVisible = ref(false);
const dialogVisibleUpdateUser = ref(false);
const dialogImportVisible = ref(false);

const formInline = reactive({
  user_Name: "",
  u_Name: "",
});

interface RuleForm {
  user_Id: string;
  user_Name: string;
  user_PassWord: string;
  u_Name: string;
  job_number: string;
  user_Phone: string;
  ids: string;
}

const delData = (User_Id: string) => {
  ElMessageBox.confirm("确认要删除吗？", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    // 在确认删除时执行的操作，例如调用后端接口删除文件
    axios
      .delete(`RBAC/UserDeleteData?user_Id=${User_Id}`)
      .then((res) => {
        if (res.data.Code == 200) {
          ElMessage({
            type: "success",
            message: res.data.Message,
          });
          // 删除成功后刷新数据等操作
          tableData();
        } else {
          ElMessage.error("删除失败");
        }
      })
      .catch(() => {
        ElMessage.error("删除失败");
      });
  });
};

const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const multipleSelection = ref<RuleForm[]>([]);

const form = reactive<RuleForm>({
  user_Id: "",
  user_Name: "",
  user_PassWord: "",
  u_Name: "",
  job_number: "",
  user_Phone: "",
  ids: "",
});

const handleClose1 = (done: () => void) => {
  done();
};

const handleSizeChange = (val: number) => {
  size.value = val;
  tableData();
};

const handleCurrentChange = (val: number) => {
  page.value = val;
  tableData();
};

const handleImport = () => {};

const rules = reactive<FormRules<RuleForm>>({
  user_Name: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 30, message: "长度在2到30之间", trigger: "blur" },
  ],
  user_PassWord: [
    {
      required: true,
      message: "请输入密码",
      trigger: "change",
    },
  ],
  u_Name: [
    {
      required: true,
      message: "请输入姓名",
      trigger: "change",
    },
  ],
  job_number: [
    {
      required: true,
      message: "请输入工号",
      trigger: "change",
    },
  ],
  user_Phone: [
    {
      type: "integer",
      required: true,
      message: "请输入联系电话且联系电话必须是整数",
      trigger: "change",
    },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "联系电话格式不正确",
    },
  ],
});

const rulesUpdate = reactive<FormRules<RuleForm>>({
  user_Name: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 30, message: "长度在2到30之间", trigger: "blur" },
  ],
  user_PassWord: [
    {
      required: true,
      message: "请输入密码",
      trigger: "change",
    },
  ],
  u_Name: [
    {
      required: true,
      message: "请输入姓名",
      trigger: "change",
    },
  ],
  job_number: [
    {
      required: true,
      message: "请输入工号",
      trigger: "change",
    },
  ],
});

const getRoleList = () => {
  axios.get("Role/GetRole").then((res) => {
    roleList.value = res.data.Data;
  });
};

const edit = (User_Id: string) => {
  dialogVisibleUpdateUser.value = true; // 打开弹窗
  console.log(form.ids);
  axios.get(`RBAC/GetUserSel?userId=${User_Id}`).then((res) => {
    if (res.data.Code == 200) {
      const bomInfo = res.data.Data;
      form.user_Id = bomInfo.User_Id; // 将主键ID存储到form中
      form.user_Name = bomInfo.User_Name;
      form.user_PassWord = bomInfo.User_PassWord;
      form.u_Name = bomInfo.U_Name;
      form.job_number = bomInfo.Job_number;
      form.user_Phone = bomInfo.User_Phone;
      form.ids = bomInfo.ids.toString().split(",");
    }
  });
};

const updateUser = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      axios.put(`RBAC/UpdateUser`, form).then((res) => {
        if (res.data.Code == 200) {
          ElMessage.success("用户修改成功");
          dialogVisibleUpdateUser.value = false; // 关闭弹窗
          window.location.reload();
        } else {
          ElMessage.error("用户修改失败");
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const addUser = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      form.ids = checkList.value.join(",");
      axios.post("RBAC/AddUser", form).then((res) => {
        if (res.data.Code == 200) {
          ElMessage.success(res.data.Message);
          dialogVisible.value = false;
        } else {
          ElMessage.error("添加失败");
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const exportExcel = () => {
  window.location.href = "Users/ExportToExcel";
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const handleSelectionChange = (val: RuleForm[]) => {
  multipleSelection.value = val;
};
const batchDel = () => {
  ElMessageBox.confirm("确认要删除吗？", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    if (multipleSelection.value.length == 0) {
      ElMessage.error("请至少选择要删除的用户！");
      return;
    }
    // 在确认删除时执行的操作，例如调用后端接口删除文件
    axios
      .put(`RBAC/BatchDeleteData`, multipleSelection.value)
      .then((res) => {
        if (res.data.Code == 200) {
          ElMessage({
            type: "success",
            message: res.data.Message,
          });
          // 删除成功后刷新数据等操作
          tableData();
        } else {
          ElMessage.error("删除失败");
        }
      })
      .catch(() => {
        ElMessage.error("删除失败");
      });
  });
};

const handleClose = (done: () => void) => {
  done();
};
const tableData = () => {
  axios
    .get("RBAC/GetUserListByKeyword", {
      params: {
        user_Name: formInline.user_Name,
        u_Name: formInline.u_Name,
        page: page.value,
        size: size.value,
      },
    })
    .then((res) => {
      userList.value = res.data.Data;
      totalCount.value = res.data.TotalCount;
    });
};

getRoleList();
tableData();
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
#app {
  line-height: 20px;
}
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>
